package com.flowplan.common.config;

import org.springframework.cache.CacheManager;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.cache.RedisCacheConfiguration;
import org.springframework.data.redis.cache.RedisCacheManager;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.RedisSerializationContext;
import org.springframework.data.redis.serializer.StringRedisSerializer;

import java.time.Duration;
import java.util.HashMap;
import java.util.Map;

/**
 * 缓存配置
 * 优化API响应性能，目标响应时间<500ms
 */
@Configuration
@EnableCaching
public class CacheConfig {

    @Bean
    public CacheManager cacheManager(RedisConnectionFactory redisConnectionFactory) {
        // 默认缓存配置
        RedisCacheConfiguration defaultConfig = RedisCacheConfiguration.defaultCacheConfig()
                .entryTtl(Duration.ofMinutes(30)) // 默认30分钟过期
                .serializeKeysWith(RedisSerializationContext.SerializationPair
                        .fromSerializer(new StringRedisSerializer()))
                .serializeValuesWith(RedisSerializationContext.SerializationPair
                        .fromSerializer(new GenericJackson2JsonRedisSerializer()))
                .disableCachingNullValues();

        // 针对不同缓存设置不同的过期时间
        Map<String, RedisCacheConfiguration> cacheConfigurations = new HashMap<>();
        
        // 项目信息缓存 - 1小时
        cacheConfigurations.put("projects", defaultConfig.entryTtl(Duration.ofHours(1)));
        
        // 用户信息缓存 - 2小时
        cacheConfigurations.put("users", defaultConfig.entryTtl(Duration.ofHours(2)));
        
        // Todo列表缓存 - 15分钟
        cacheConfigurations.put("todos", defaultConfig.entryTtl(Duration.ofMinutes(15)));
        
        // Excel解析结果缓存 - 1小时
        cacheConfigurations.put("excel-parse", defaultConfig.entryTtl(Duration.ofHours(1)));
        
        // AI分析结果缓存 - 24小时
        cacheConfigurations.put("ai-analysis", defaultConfig.entryTtl(Duration.ofHours(24)));
        
        // 统计数据缓存 - 5分钟
        cacheConfigurations.put("statistics", defaultConfig.entryTtl(Duration.ofMinutes(5)));

        return RedisCacheManager.builder(redisConnectionFactory)
                .cacheDefaults(defaultConfig)
                .withInitialCacheConfigurations(cacheConfigurations)
                .build();
    }
}